#include <iostream> 
#include <fstream>
#include <vector>
#include <string>
#include <dirent.h>
#include <sys/stat.h>

#include "dir.h"
#include "fs-archive.h"

using namespace std;

void CDir::refresh() {
  cerr << "-> CDir::refresh" << endl;
  ve.clear();
  DIR *pd = opendir(Name().c_str());
  if (NULL == pd) return;
  dirent *pde = NULL;
  while (NULL != (pde = readdir(pd))) {
    IEntry *pe = filesystem.Create(Name() + "/" + pde->d_name);
    if (NULL == pe) 
      cerr << "pe is NULL :(" << endl;
    ve.push_back(pe);
  }
  closedir(pd); 
  cerr << "<- CDir::refresh" << endl;
}

void CTextFile::read() {
  ifstream f(Name().c_str());
  if (!f.is_open()) 
    return;
    //throw;
  while (!f.eof()) {
    string s;
    getline(f, s);
    vl.push_back(s);
  }
}

void* CFile::read_from_disk() {
  if (NULL != pdata)
    throw;

  ifstream f(Name().c_str(), ios::binary);
  if (!f.is_open())
    return NULL;

  //ifstream::pos_type length = 0;
  int length = 0;
  f.seekg(0, ios::end);
  length = f.tellg(); 
  f.seekg(0, ios::beg);

  void *p = new char[length + 1];
  memset(p, 0, length + 1);

  if (NULL == p)
    throw;

  if (!f.read((char*)p, length))
    throw;

  sz = length + 1;

  return p;
}

IEntry* CFSEntryFactory::Create(const std::string &name) const {
  struct stat s;
  lstat(name.c_str(), &s);
  if (S_ISREG(s.st_mode)) {
    size_t p = 0;
    while (std::string::npos != (p = name.find('.', p+1))) {
      std::string ext = name.substr(p + 1);
      cerr << "ext = " << ext << endl;
      if (std::string("tar.bz2") == ext || std::string("zip") == ext) 
        return new CArch(name);
      if (std::string("txt") == ext || std::string("cpp") == ext)
        return new CTextFile(name);
    }
    return new CFile(name);
  } else if (S_ISDIR(s.st_mode)) {
    return new CDir(name);
  } else 
    return NULL;
}

CFSEntryFactory filesystem;
